/*
 * @(#)DmsNewVersion.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.action;

import java.sql.Connection;

import org.quartz.JobDataMap;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.EventLogger;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.workflow.WorkflowErrorConstant;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.core.WorkflowProcessor;

/**
 * DmsNewVersion.java
 *
 * This class is the automatic task handler for publish public document.
 *
 * @author      Angus Shiu
 * @company     DCIVision Limited
 * @creation date   26/01/2003
 * @version     $Revision: 1.14.2.1 $
 */

public class DmsNewVersion extends com.dcivision.workflow.core.WorkflowProcessor {

  public static final String REVISION = "$Revision: 1.14.2.1 $";

  public DmsNewVersion() {
    this.numOfRoutine = 1;
    this.labelType = WorkflowProcessor.LABEL_TYPE_USER_DEFINE;
    this.labelString = new String[] {"workflow.label.step_status_G"};
  }

  public synchronized void execute(JobDataMap dataMap, WorkflowProgress currentProgress) throws ApplicationException {
    log.info("***** DmsNewVersion workflow processor BEGIN *****");
    Connection conn = null;

    Integer trigerEventUserID = new Integer(0);
    String serverName = "127.0.0.1";
    String functionName = SystemFunctionConstant.WORKFLOW_TASK;
    String errorMessage = "";

    try {
      //* get the DB Connection
      SessionContainer sessionCon = this.getSessionContainer();

      /*************************************************************
       *  get Event Log Information Begin
       *************************************************************/
      if (!Utility.isEmpty(sessionCon.getUserRecordID())) {
        trigerEventUserID = sessionCon.getUserRecordID();
      }

      if (!Utility.isEmpty(sessionCon.getUserIPAddress())) {
        serverName = sessionCon.getUserIPAddress();
      }
      errorMessage =  "DmsNewVersion.java -- Track ID: " + currentProgress.getTrackID() +
                      ", Workflow Progress ID : " + currentProgress.getID() +
                      ", Workflow Step ID: " + currentProgress.getWorkflowStepID() +
                      "<br> ";
      /*************************************************************
       *  get Event Log Information End
       *************************************************************/
      //for schedule job useing the processer connection.
      isLocalConnection = false;
      if(!Utility.isEmpty(this.getConnection())){
        conn = this.getConnection();
      }else{
        isLocalConnection = true;
        conn = DataSourceFactory.getConnection();
      }
      /**====================================
      //* create required DAObject
      WorkflowProgressDAObject progressDAO = new WorkflowProgressDAObject(sessionCon, conn);
      WorkflowProgressAttachmentDAObject progressAttachDAO = new WorkflowProgressAttachmentDAObject(sessionCon, conn);
      UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionCon, conn);
      MtmWfProgressWfProgressDAObject mtmWfProgressWfProgressDAO = new MtmWfProgressWfProgressDAObject(sessionCon, conn);
      WorkflowProgress prevProgress = new WorkflowProgress();
      //* get relevant information from
      AbstractBaseObject workflowObject = (AbstractBaseObject) dataMap.get("WORKFLOW_OBJECT");
log.debug("workflow object class name: "+workflowObject.getClass().getName());
      Map objParamMap = (Map) dataMap.get("OBJECT_PARAMETER");
log.debug("object parameter map: "+objParamMap);
      String ipaddress = (String) objParamMap.get("DOC_CHECKIN_IPADDRESS");
      String sessionID = (String) objParamMap.get("DOC_CHECKIN_SESSIONID");
log.debug("User IP Addr = "+ipaddress);
      sessionCon.setUserIPAddress(ipaddress);
      Integer docID = workflowObject.getID();

      //* do what you want below
      // ADD BY DICK
      // TODO get pre progress through MTM_WF_PROGRESS_WF_PROGRESS
      List parentProgressList = mtmWfProgressWfProgressDAO.getListByChildProgressID(currentProgress.getID());
      if (!Utility.isEmpty(parentProgressList)) {
        MtmWfProgressWfProgress mtmWfProgressWfProgress = (MtmWfProgressWfProgress)parentProgressList.get(parentProgressList.size()-1);
        prevProgress = (WorkflowProgress)progressDAO.getObjectByID(mtmWfProgressWfProgress.getParentProgressID());
      }
      // END BY DICK
      log.info("previous progress id: " + prevProgress.getID());
      Integer userRecordID = prevProgress.getUpdaterID();
      log.info("user record id: "+userRecordID);
      UserRecord userRecord = (UserRecord) userRecordDAO.getObjectByID(userRecordID);
      sessionCon.setUserRecord(userRecord);
      List docList = progressAttachDAO.getListByWorkflowProgressID(prevProgress.getID());

      DmsDocumentDAObject docDAO = new DmsDocumentDAObject(sessionCon, conn);
      WorkflowProgressManager progressManager = new WorkflowProgressManager(sessionCon, conn);
      VersionControlManager versionManager = new VersionControlManager(sessionCon, conn);

      for (int i=0; i<docList.size(); i++) {
        WorkflowProgressAttachment tmpProgressAttach = (WorkflowProgressAttachment) docList.get(i);
        if (tmpProgressAttach.getAttachmentType().equals(WorkflowProgressAttachment.ATTACHED_SINGLE_FILE)) {
          log.info("get the correct one");
          WorkflowProgressAttachment newDocVersion = progressManager.getWorkflowProgressAttachmentWithContent(tmpProgressAttach.getID());
          log.info("get the file content input stream");
          InputStream inputStream = newDocVersion.getDataStream();
          Integer contentSize = newDocVersion.getContentSize();
          log.info("content size: "+contentSize);

          log.info("document id: "+docID);
          DmsDocument document = (DmsDocument) docDAO.getObjectByID(docID);
          log.info("got the dms document");

          versionManager.checkoutDocument(DmsVersion.EXCLUSIVE_LOCK, document);
          conn.commit();
          log.info("commit check out");

          DmsVersion dmsVersion = new DmsVersion();
          dmsVersion.setItemSize(contentSize);
          dmsVersion.setDocumentID(document.getID());
          dmsVersion.setReferenceNo(document.getReferenceNo());
          dmsVersion.setDescription(document.getDescription());
          dmsVersion.setVersionLabel(newDocVersion.getAttachmentName());
          dmsVersion.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
          // setting parent id = 0 means a major checkin
          //dmsVersion.setParentID(new Integer(0));

          versionManager.checkinDocument(true, DmsOperationConstant.CREATE_NEW_CHECKIN, document.getID(), dmsVersion, inputStream);
          log.info("commit");
          break;
        }
      }
      ==================================**/
      //* after the execution, set the desired appropriate out number
      this.returnRoutineIndex = 1; //* should be between 0 and numOfRoutine-1
      //* if need to auto-Execute the following step, set the below variable to true (default false)
      this.bAutoExecuteNextStep=false; this.bCreateNextWorkflowProgress=true;

      if(isLocalConnection){
        conn.commit();
      }
    } catch (ApplicationException appEx) {
      log.error("Application exception:\n"+appEx);
      /***********************************
       *  Record the Event Log.
       ***********************************/
      EventLogger.logEventMessage(trigerEventUserID, serverName, errorMessage, appEx.getMsgCode(), WorkflowErrorConstant.LOG_AUTO_TASK_ERROR_CODE, functionName, appEx.toString() );

      throw appEx; //* prop
    } catch (Exception e) {
      log.error("Error during processing this automatic task.", e);
      /***********************************
       *  Record the Event Log.
       ***********************************/
      EventLogger.logEventMessage(trigerEventUserID, serverName, errorMessage, ErrorConstant.COMMON_FATAL_ERROR, WorkflowErrorConstant.LOG_AUTO_TASK_ERROR_CODE, functionName, e.toString() );

      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR); //* throw an applicationExcpetion with an appropriate
    } finally {
      if(isLocalConnection){
        try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
      }
    }

    log.info("***** DmsNewVersion workflow processor END   *****");
  }

}
